package com.hhf.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhf.springboot.annotation.AuthCheck;
import com.hhf.springboot.common.*;
import com.hhf.springboot.constant.UserConstant;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.model.dto.orderInfo.*;
import com.hhf.springboot.model.entity.OrderInfo;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.enums.OrderInfoStatusEnum;
import com.hhf.springboot.model.vo.OrderInfoVO;
import com.hhf.springboot.service.OrderInfoService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;

/**
 * 订单信息接口
 *
 * @author hhf
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/orderInfo")
@Slf4j
public class OrderInfoController {

    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private UserService userService;


    /**
     * 获取销售额统计数据
     * @return
     */
    @GetMapping("/sales/statistics")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<SalesStatisticsDTO> getSalesStatistics() {
        SalesStatisticsDTO salesStatistics = orderInfoService.getSalesStatistics();
        return Result.success(salesStatistics);
    }


    /**
     * 获取 orderInfo 的总的数量
     * @return
     */
    @GetMapping("/count")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> getTotalCount(){
        return Result.success(orderInfoService.count());
    }


    /**
     * 处理过期订单
     *
     * @param orderInfoExpiredRequest
     * @return
     */
    @PostMapping("/expired")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateExpiredOrderInfo(@RequestBody OrderInfoExpiredRequest orderInfoExpiredRequest) {
        if (orderInfoExpiredRequest == null || orderInfoExpiredRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoExpiredRequest, orderInfo);
        // 判断是否存在
        long id = orderInfoExpiredRequest.getId();
        OrderInfo oldOrderInfo = orderInfoService.getById(id);
        ThrowUtils.throwIf(oldOrderInfo == null, ErrorCode.NOT_FOUND_ERROR);
        if (OrderInfoStatusEnum.NO_PAY.getValue().equals(oldOrderInfo.getStatus())) {
            // 修改status
            orderInfo.setStatus(OrderInfoStatusEnum.HAS_CANCEL.getValue());
        }
        // 操作数据库
        boolean result = orderInfoService.updateById(orderInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }


    // region 增删改查

    /**
     * 创建订单信息
     *
     * @param orderInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addOrderInfo(@RequestBody OrderInfoAddRequest orderInfoAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(orderInfoAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoAddRequest, orderInfo);
        // 数据校验
        orderInfoService.validOrderInfo(orderInfo, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        orderInfo.setUserId(loginUser.getId());
        orderInfo.setStatus(OrderInfoStatusEnum.NO_PAY.getValue());
        // 填充其它信息(amount,orderNo,transactionId)
        orderInfo = orderInfoService.fillOrderInfo(orderInfo);

        // 写入数据库
        boolean result = orderInfoService.save(orderInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newOrderInfoId = orderInfo.getId();
        return Result.success(newOrderInfoId);
    }

    /**
     * 删除订单信息
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteOrderInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        OrderInfo oldOrderInfo = orderInfoService.getById(id);
        ThrowUtils.throwIf(oldOrderInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldOrderInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = orderInfoService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新订单信息（仅管理员可用）
     *
     * @param orderInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateOrderInfo(@RequestBody OrderInfoUpdateRequest orderInfoUpdateRequest) {
        if (orderInfoUpdateRequest == null || orderInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoUpdateRequest, orderInfo);
        // 数据校验
        orderInfoService.validOrderInfo(orderInfo, false);
        // 判断是否存在
        long id = orderInfoUpdateRequest.getId();
        OrderInfo oldOrderInfo = orderInfoService.getById(id);
        ThrowUtils.throwIf(oldOrderInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = orderInfoService.updateById(orderInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取订单信息（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<OrderInfoVO> getOrderInfoVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        OrderInfo orderInfo = orderInfoService.getById(id);
        ThrowUtils.throwIf(orderInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(orderInfoService.getOrderInfoVO(orderInfo, request));
    }

    /**
     * 分页获取订单信息列表（仅管理员可用）
     *
     * @param orderInfoQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<OrderInfo>> listOrderInfoByPage(@RequestBody OrderInfoQueryRequest orderInfoQueryRequest) {
        long current = orderInfoQueryRequest.getCurrent();
        long size = orderInfoQueryRequest.getPageSize();
        // 查询数据库
        Page<OrderInfo> orderInfoPage = orderInfoService.page(new Page<>(current, size),
                orderInfoService.getQueryWrapper(orderInfoQueryRequest));
        return Result.success(orderInfoPage);
    }

    /**
     * 分页获取订单信息列表（封装类）
     *
     * @param orderInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<OrderInfoVO>> listOrderInfoVOByPage(@RequestBody OrderInfoQueryRequest orderInfoQueryRequest,
                                                                 HttpServletRequest request) {
        long current = orderInfoQueryRequest.getCurrent();
        long size = orderInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<OrderInfo> orderInfoPage = orderInfoService.page(new Page<>(current, size),
                orderInfoService.getQueryWrapper(orderInfoQueryRequest));
        // 获取封装类
        return Result.success(orderInfoService.getOrderInfoVOPage(orderInfoPage, request));
    }

    /**
     * 分页获取当前登录用户创建的订单信息列表
     *
     * @param orderInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<OrderInfoVO>> listMyOrderInfoVOByPage(@RequestBody OrderInfoQueryRequest orderInfoQueryRequest,
                                                                   HttpServletRequest request) {
        ThrowUtils.throwIf(orderInfoQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        orderInfoQueryRequest.setUserId(loginUser.getId());
        long current = orderInfoQueryRequest.getCurrent();
        long size = orderInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<OrderInfo> orderInfoPage = orderInfoService.page(new Page<>(current, size),
                orderInfoService.getQueryWrapper(orderInfoQueryRequest));
        // 获取封装类
        return Result.success(orderInfoService.getOrderInfoVOPage(orderInfoPage, request));
    }

    /**
     * 编辑订单信息（给用户使用）
     *
     * @param orderInfoEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editOrderInfo(@RequestBody OrderInfoEditRequest orderInfoEditRequest, HttpServletRequest request) {
        if (orderInfoEditRequest == null || orderInfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoEditRequest, orderInfo);
        // 数据校验
        orderInfoService.validOrderInfo(orderInfo, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = orderInfoEditRequest.getId();
        OrderInfo oldOrderInfo = orderInfoService.getById(id);
        ThrowUtils.throwIf(oldOrderInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldOrderInfo.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = orderInfoService.updateById(orderInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 日新增统计订单信息
     *
     * @return
     */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedOrderInfo() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> orderInfoDataList = orderInfoService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(orderInfoDataList);

    }

    // endregion
}

